package net.grandcentrix.thirtyinch.sample.fragmentlifecycle;

import net.grandcentrix.thirtyinch.TiLog;
import net.grandcentrix.thirtyinch.sample.ResourceTable;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;

import java.util.ArrayList;

public class LifecycleViewPagerActivity extends FractionAbility {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        TiLog.i("LifecycleViewPagerActivity", "onStart");
        setUIContent(ResourceTable.Layout_viewpager);
        PageSlider viewPager= (PageSlider) findComponentById(ResourceTable.Id_pageViewer);
        FractionManager manager = getFractionManager();
        viewPager.setProvider(new PagerAdapter(manager));
    }
}

class PagerAdapter extends PageSliderProvider {

    FractionManager manager ;
    public PagerAdapter( FractionManager manager) {
        this.manager = manager;
    }

    ArrayList<TestFragmentA> fragments = new ArrayList<>();

    {
        fragments.add(new TestFragmentA());
        fragments.add(new TestFragmentA());
        fragments.add(new TestFragmentA());
        fragments.add(new TestFragmentA());
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        TiLog.d("LifecycleViewPagerActivity", "createPageInContainer" );
        StackLayout layout = new StackLayout(componentContainer.getContext());
        layout.setLayoutConfig(
                new StackLayout.LayoutConfig(
                        ComponentContainer.LayoutConfig.MATCH_PARENT,
                        ComponentContainer.LayoutConfig.MATCH_PARENT
                ));
        layout.setId(ResourceTable.String_zzz + i);
        componentContainer.addComponent(layout);

        manager.startFractionScheduler().add(ResourceTable.String_zzz + i, fragments.get(i)).submit();
        return fragments.get(i);
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
//        componentContainer.removeComponent((Component) o);
        manager.startFractionScheduler().remove(fragments.get(i)).submit();
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        TiLog.i("LifecycleViewPagerActivity", "isPageMatchToObject" + component + " "+ o);
        if(o instanceof Fraction){
            return ((Fraction)o).getComponent() == o;
        }
        return false;
    }
}

